package com.zzg.test2.web

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.RenderProcessGoneDetail
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import com.zzg.test2.R

class TabWebJsFragment  : Fragment() {
    val TAG = "TabWebJsFragment"
    private lateinit var webView: WebView
    private var url: String = ""

    companion object {
//        @SuppressLint("StaticFieldLeak")
//        var webJsFragment: TabWebJsFragment? = null
        fun  newInstance(url: String): TabWebJsFragment {
//            if (webJsFragment == null){
              val  webJsFragment = TabWebJsFragment()
                val args = Bundle()
                args.putString("url", url)
                webJsFragment!!.arguments = args
//            }

            return webJsFragment!!
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            url = it.getString("url", "")
        }

        requireActivity().onBackPressedDispatcher.addCallback(this,object:OnBackPressedCallback(true){
            override fun handleOnBackPressed() {
                if (!::webView.isInitialized || webView == null){
                    requireActivity().onBackPressed() // 调用系统默认行为
                }

                if (  webView.canGoBack()) {
                    webView.goBack()
                } else {
//                    isEnabled = false // 禁用回调
//                    requireActivity().onBackPressed() // 调用系统默认行为
                    return@handleOnBackPressed
                }
            }
        } )
    }

    var frameLayout: FrameLayout? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_web, container, false)
        frameLayout = view.findViewById<FrameLayout>(R.id.web_frameLayout)
//        webView = view.findViewById(R.id.webView)
        webView = WebView(requireContext())
        frameLayout!!.addView(webView)
//        initWebView()
        WebSetting.setWebSetting(webView)
        setWebClient()
        Log.d("webView", "onCreateView initWebView = $url")
        webView.loadUrl(url)
        return view
    }

    fun reloadWebView(refreshUrl : String) {
        this.url = refreshUrl
        if (::webView.isInitialized && webView != null){
            Log.d("webView", "reloadWebView loadUrl = $url")
            webView.loadUrl(url)
        }

    }
    private fun initWebView() {
        val settings = webView.settings
        settings.javaScriptEnabled = true
        // 设置缓存模式，针对华为手机做处理
        settings.cacheMode = WebSettings.LOAD_DEFAULT


//        // 2. 启用现代存储机制（替代废弃的AppCache）
//        // 2. 启用现代存储机制（替代废弃的AppCache）
//        // DOM Storage 和 Web SQL Database
//        settings.domStorageEnabled = true
//        settings.databaseEnabled = true
//
//        // 设置数据库存储路径（可选）
//        val dbPath: String =
//            requireContext().getDir("web_db", Context.MODE_PRIVATE).getPath()
//        settings.databasePath = dbPath
//
//// 3. 启用文件存储（替代AppCache）
//
//// 3. 启用文件存储（替代AppCache）
//        settings.allowFileAccess = true
//        settings.allowContentAccess = true


        // 限制缓存大小（单位：字节）
        settings.setAppCacheMaxSize(10 * 1024 * 1024); // 10MB
        // 启用/禁用缓存（确保缓存可用）
        // 启用/禁用缓存（确保缓存可用）
        settings.setAppCacheEnabled(true)
        // 启用数据库缓存
        settings.databaseEnabled = true
        // 启用 DOM 存储
        settings.domStorageEnabled = true
        // 指定AppCache路径（避免使用内部缓存目录）
        // 指定AppCache路径（避免使用内部缓存目录）
        val cachePath: String =
            requireContext().getCacheDir().getAbsolutePath() + "/web_cache"
        settings.setAppCachePath(cachePath)
        // 检测华为设备并降低内存使用
        if (Build.MANUFACTURER.equals("huawei", ignoreCase = true)) {
            // 减少缓存压力
            settings.setAppCacheEnabled(false);

            // 启用华为专用兼容模式
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE;
            }
        }

        // 合理设置内存缓存
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        val userAgent =
            webView.settings.userAgentString + "/leadbank|APP|MerchmAppH5|5.5.2"
        settings.userAgentString = userAgent
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                url?.let { view?.loadUrl(it) }
                Log.d(TAG, "shouldOverrideUrlLoading: $url")
                return true
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                // 处理页面加载错误
//                handleWebViewError(view, error)
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
//                 处理HTTP错误
//                handleHttpError(view, errorResponse)
            }
        }
    }

    private fun setWebClient(){
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                url?.let { view?.loadUrl(it) }
                Log.d(TAG, "shouldOverrideUrlLoading: $url")
                return true
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                // 处理页面加载错误
//                handleWebViewError(view, error)
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
//                 处理HTTP错误
//                handleHttpError(view, errorResponse)
            }


            override fun onRenderProcessGone(view: WebView?, detail: RenderProcessGoneDetail?): Boolean {
                if (view == webView) {
                    Log.e(TAG, "崩溃了，——————Render process crashed, reloading...")
                    handleWebViewCrash()
                    return true
                }
                return false
            }
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.e(TAG, "加载完成  onPageFinished")
//                isWebViewPaused = false
            }

        }
    }

    //    private fun handleRenderProcessGone(webView: WebView, detail: WebViewRenderProcessGoneDetail) {
//        // 检查是否需要重新创建WebView
//        if (detail.didCrash()) {
//            Log.e("WebView", "Render process crashed, reloading...")
//            // 重新加载页面或显示错误页面
//            reloadWebView(webView)
//        } else {
//            Log.w("WebView", "Render process killed by system")
//            // 系统回收内存导致的终止
//            recreateWebView(webView)
//        }
//    }


    override fun onResume() {
        super.onResume()
        webView.onResume()
    }



    override fun onPause() {
        super.onPause()
        webView.onPause()
    }

   override fun onDestroyView() {
        if (::webView.isInitialized) {
            try {
                webView.apply {
                    stopLoading()
                    onPause()
                    removeAllViews()
                    destroy()
                }
            } catch (e: Exception) {
                Log.w("TabWebJsFragment", "Error destroying WebView", e)
            }
        }
        super.onDestroyView()
    }

    private fun handleWebViewCrash() {
        try {
            // 清理崩溃的WebView
            if (::webView.isInitialized) {
                webView.destroy()

            }

//            val frameLayout = findViewById<FrameLayout>(R.id.web_frameLayout)
//        webView = view.findViewById(R.id.webView)
            webView = WebView(requireContext())
            frameLayout!!.addView(webView)
            webView.loadUrl(url)
//
//            // 重新创建WebView（可选）
//            val parent = view?.findViewById<ViewGroup>(R.id.webView)?.parent as? ViewGroup
//            parent?.let {
//                // 显示错误提示或重新加载页面
//                // 可以创建新的WebView实例替换
//            }

        } catch (e: Exception) {
            Log.e("TabWebJsFragment", "Error handling WebView crash", e)
        }
    }
}